/**
 *
 * 路由鉴权
 */
import {
	getCookieValue
} from '~/util/index.js';
import aes from '~/util/aes.js'
export default function ({
  route,
  req,
  res,
  redirect,
  app
}) {
  let isServer = process.server
  let isClient = process.client
  let redirectURL = '/' // 默认跳转到后台管理的登录页
  let token, path, fullPath;

  // 在服务端
  if (isServer) { 
    let cookies = req.headers.cookie;
		token = getCookieValue('token', cookies);
    path = req.url.split('?')[0];
    fullPath = req.originalUrl;
  }

  // 在客户端
  if (isClient) {
    token = app.$cookies.get('token');
    path = route.path;
    fullPath = escape(route.fullPath);
  }

  /*
  * 判断是否登录，采用白名单政策（不在数组中即需要验证是否登录，没有登录跳转到登录页）
  * 判断路由得判断不带query的那一部分路径path，跳转到登录页时带上全路径 fullPath
  */
 
  let whitelist = [
    '/',
    '/login',
    '/test'
  ]
  if (whitelist.indexOf(path) === -1) {
    if(token) {
      return
    } else {
      redirect(redirectURL + 'login')
    }
  } else {
    return
  }
}
